package com.example.index.web;


import com.example.index.web.feign.IUserAction;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;

@RestController
public class IndexAction {



    @RequestMapping("index")
    public  String index(HttpServletRequest request){
        return "index: "+request.getServerPort();
    }

    @Resource
    RestTemplate restTemplate;
    @RequestMapping("user")
    public String user(){
        String ret = restTemplate.getForObject("http://user/user", String.class);
        return "远程访问user:"+ret;
    }
    @Resource
    IUserAction userAction;
    @RequestMapping("userByAction")
    public String user1(){
        return "远程访问user:"+userAction.user();
    }

    @RequestMapping("hello")
    public String hello(String name){return userAction.hello(name);}

    @RequestMapping("add")
    public int add(int a,int b){return userAction.add(a,b);}

    @RequestMapping("reg")
    public User add(){
        User user = new User("zhangsan", 18, new Date(), new String[]{"唱歌", "跳舞", "看书"});
        return userAction.reg(user);
    }

    @RequestMapping("path/{ptest}")
    public String ptest(@PathVariable("ptest") String ptest){
        return userAction.ptest(ptest);
    }


    @RequestMapping("headers")
    public void headers(HttpServletRequest request, HttpServletResponse response, PrintWriter out){
        response.setContentType("text/html;charset=utf-8");
        out.println("<ul>");

        Enumeration<String> headerNames = request.getHeaderNames();

        while(headerNames.hasMoreElements()){
            String name = headerNames.nextElement();
            out.println("<li>");
            out.println(name+":"+ request.getHeader(name));
            out.println("</li>");
        }

        out.println("</ul>");

        Cookie cookie = new Cookie("name", "zhangsan");
        cookie.setMaxAge(99999);
        response.addCookie(cookie);
    }
}
